<?php
namespace backend\logic;

use think\Db;
use external\SFTools;
use think\db\Where;

class DispatchLogic {
    
    /**
     * 获取制令信息列表
     * @param   string $keyword 关键字
     * @param   int    $page    页码
     * @param   int    $size    每页大小
     * @return  array           数组对象数据
     * */
    public function getMoList($keyword, $fPlanDate, $fStartDate, $fEndDate, $cw, $ct, $wg, $page, $size){
        if ((!empty($fStartDate) && empty($fEndDate)) || (empty($fStartDate) && !empty($fEndDate))) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate, "fEndDate" => $fEndDate));
        }
        $where = new Where();
        if (!empty($fStartDate) && !empty($fEndDate)) {
            $where['fOpenDate'] = ['between', [$fStartDate, $fEndDate]];
        } else {
            if (empty($fPlanDate)) {
                return SFTools::err("3300", array("fPlanDate" => $fPlanDate));
            }
            $where['fPlanEndDate'] = $fPlanDate;
        }
        if (!empty($keyword)) {
            $where['fMONo | fGoodsCode'] = array('like', '%' . $keyword . '%');
        }
        $whereColumn[] = ['1', '=', '1'];
        if (!empty($ct)) {
            if ($ct == '1') {
                $whereColumn[] = ['fStep01', '>', 0];
                $whereColumn[] = ['fMoQty', '>', 'fStep01'];
            }
            if ($ct == '2') {
                $whereColumn[] = ['fMoQty', '=', 'fStep01'];
            }
            if ($ct == '3') {
                $whereColumn[] = ['fStep01', '=', 0];
            }
        }
        if (!empty($cw)) {
            if ($cw == '1') {
                $whereColumn[] = ['fStep02', '>', 0];
                $whereColumn[] = ['fMoQty', '>', 'fStep02'];
            }
            if ($cw == '2') {
                $whereColumn[] = ['fMoQty', '=', 'fStep02'];
            }
            if ($cw == '3') {
                $whereColumn[] = ['fStep02', '=', 0];
            }
        }
        if (!empty($wg)) {
            if ($wg == '1') {
                $whereColumn[] = ['fMoQty', '=', 'fProStkInQty'];
            }
            if ($wg == '2') {
                $whereColumn[] = ['fMoQty', '>', 'fProStkInQty'];
            }
        }
        $goodsLogic = new \backend\logic\GoodsLogic();
        $moList = Db::table('v_mo_mst_cd_list')->field('*')->where($where)->whereColumn($whereColumn)->page($page, $size)->order(['sort' => 'desc', 'fModelNameCW' => 'desc', 'fModelNameCT' => 'desc'])->select();
        //$moList = Db::table('v_mo_mst_cd_list')->field('*')->where($where)->whereColumn($whereColumn)->whereTime('fOpenDate', 'between', [$fStartDate, $fEndDate])->page($page, $size)->order(['sort' => 'desc', 'fOpenDate' => 'ASC', 'fMONo' => 'ASC'])->select();
        foreach ($moList as $key => $val) {
            if ($val['fIsNotCount'] == '0') {
                $fGoodsID = $val['fGoodsID'];
                $fGoodsCode = $val['fGoodsCode'];
                $productionBomFind = $goodsLogic->getBomFind($fGoodsID, $fGoodsCode);
                if (!empty($productionBomFind)) {
                    $moList[$key]['fIsNotCount'] = '1';
                    $moList[$key]['fModelCodeCT'] = $productionBomFind['fModelCodeCT'];
                    $moList[$key]['fModelNameCT'] = $productionBomFind['fModelNameCT'];
                    $moList[$key]['fModelCodeCW'] = $productionBomFind['fModelCodeCW'];
                    $moList[$key]['fModelNameCW'] = $productionBomFind['fModelNameCW'];
                }
            }
        }
        
        return $moList;
    }
    
    /**
     * 获取制令信息列表
     * @param   string $keyword 关键字
     * @return  array           数组对象数据
     * */
    public function getMoListCountBuyKeyword($keyword, $fPlanDate, $fStartDate, $fEndDate, $cw, $ct, $wg){
        if ((!empty($fStartDate) && empty($fEndDate)) || (empty($fStartDate) && !empty($fEndDate))) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate, "fEndDate" => $fEndDate));
        }
        $where = new Where();
        if (!empty($fStartDate) && !empty($fEndDate)) {
            $where['fOpenDate'] = ['between', [$fStartDate, $fEndDate]];
        } else {
            if (empty($fPlanDate)) {
                return SFTools::err("3300", array("fPlanDate" => $fPlanDate));
            }
            $where['fPlanEndDate'] = $fPlanDate;
        }
        if (!empty($keyword)) {
            $where['fMONo | fGoodsCode'] = array('like', '%' . $keyword . '%');
        }
        $whereColumn[] = ['1', '=', '1'];
        if (!empty($ct)) {
            if ($ct == '1') {
                $whereColumn[] = ['fMoQty', '=', 'fStep01'];
            }
            if ($ct == '2') {
                $whereColumn[] = ['fMoQty', '<>', 'fStep01'];
            }
        }
        if (!empty($cw)) {
            if ($cw == '1') {
                $whereColumn[] = ['fMoQty', '=', 'fStep02'];
            }
            if ($cw == '2') {
                $whereColumn[] = ['fMoQty', '<>', 'fStep02'];
            }
        }
        if (!empty($wg)) {
            if ($wg == '1') {
                $whereColumn[] = ['fMoQty', '=', 'fProStkInQty'];
            }
            if ($wg == '2') {
                $whereColumn[] = ['fMoQty', '<>', 'fProStkInQty'];
            }
        }
        
        //return Db::table('v_mo_mst_cd_list')->where($where)->whereColumn($whereColumn)->whereTime('fOpenDate', 'between', [$fStartDate, $fEndDate])->count();
        return Db::table('v_mo_mst_cd_list')->where($where)->whereColumn($whereColumn)->count();
    }
    
    /**
     * 修改生产工作记录
     * @param   string $fMONo    制令编号
     * @param   int    $fGoodsID 商品标识
     * @param   int    $sort     排序权重
     * @param   int    $fPlanCountCw  床网所需数量
     * @return  array            数组对象数据
     * */
    public function editMoInfoBuyfMONoANDfGoodsID($fMONo, $fGoodsID, $sort, $fPlanCountCw = ''){
        if (empty($fMONo)) {
            return SFTools::err("3300", array("fMONo" => $fMONo));
        }
        if (empty($fGoodsID)) {
            return SFTools::err("3300", array("fGoodsID" => $fGoodsID));
        }
        $productionStep = new \backend\model\ProductionStep;
        $productionStepFind = $productionStep::where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
        if (empty($productionStepFind)) {
            $productionStep->fMONo = $fMONo;
            $productionStep->fGoodsID = $fGoodsID;
            $productionStep->sort = $sort;
            if($fPlanCountCw !== '') {
                $productionStep->fPlanCountCw = $fPlanCountCw;
            }
            $productionStep->save();
        } else {
            $productionStepFind->sort = $sort;
            if($fPlanCountCw !== '') {
                $productionStepFind->fPlanCountCw = $fPlanCountCw;
            }
            $productionStepFind->update_datetime = SFTools::getTimeNow();
            $productionStepFind->save();
        }
        
        return true;
        //return  Db::table('v_mo_mst_cd_list')->where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
    }
    
    
    
    /**
     * 修改生产工作记录
     * @param   string $fMONo    制令编号
     * @param   int    $fGoodsID 商品标识
     * @param   int    $fProcessCW  床网打底工艺
     * @param   int    $sort     排序权重
     * @return  array            数组对象数据
     * */
    public function editProductionStepBuyfMONoANDfGoodsID($fMONo, $fGoodsID, $fProcessCW, $sort){
        if (empty($fMONo)) {
            return SFTools::err("3300", array("fMONo" => $fMONo));
        }
        if (empty($fGoodsID)) {
            return SFTools::err("3300", array("fGoodsID" => $fGoodsID));
        }
        $productionBom = new \backend\model\ProductionBom;
        $productionBomFind = $productionBom::where('fGoodsID', $fGoodsID)->find();
        if (!empty($productionBomFind)) {
            $productionBomFind->fProcessCW = $fProcessCW;
            $productionBomFind->save();
        }
        $productionStep = new \backend\model\ProductionStep;
        $productionStepFind = $productionStep::where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
        if (empty($productionStepFind)) {
            $productionStep->fMONo = $fMONo;
            $productionStep->fGoodsID = $fGoodsID;
            $productionStep->sort = $sort;
            $productionStep->save();
        } else {
            $productionStepFind->sort = $sort;
            $productionStepFind->update_datetime = SFTools::getTimeNow();
            $productionStepFind->save();
        }
        
        return true;
    }
    
    public function toWriteOff($fMONo, $fGoodsID, $fQtyCW){
        if (empty($fMONo)) {
            return SFTools::err("3300", array("fMONo" => $fMONo));
        }
        if (empty($fGoodsID)) {
            return SFTools::err("3300", array("fGoodsID" => $fGoodsID));
        }
        if (empty($fQtyCW) || !is_numeric($fQtyCW)) {
            return SFTools::err("3300", array("fQtyCW" => $fQtyCW));
        }
        $moFind = Db::table('v_mo_mst_cd_list')->where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
        $fModelCodeCW = $moFind['fModelCodeCW'];
        if (empty($fModelCodeCW)) {
            return SFTools::err("3300");
        }
        $where = new Where();
        $where['fModelCodeCW'] = $fModelCodeCW;
        $where['fMONo'] = ['null'];
        $snListCW = Db::table('v_sn_list_cw')->field('*')->where($where)->order('create_datetime')->select();
        if (empty($snListCW)) {
            return SFTools::err("3307", array("snListCW" => $snListCW));
        }
        $snListCount = count($snListCW);
        $fMoQty = intval($moFind['fMoQty']);
        $fStep02 = intval($moFind['fStep02']);
        $maxCountCW = $fMoQty - $fStep02;
        if ($maxCountCW < $fQtyCW || $fQtyCW < 0) {
            return SFTools::err("3307", array("maxCountCW" => $maxCountCW, "fQtyCW" => $fQtyCW));
        }
        if ($fMoQty <= $fStep02) {
            return SFTools::err("3309", array("fMoQty" => $fMoQty, "fStep02" => $fStep02));
        }
        $arrCount = $fQtyCW > $snListCount ? $snListCount : $fQtyCW;
        for ($i = 0; $i < $arrCount; $i++) {
            $productionStepCw = new \backend\model\ProductionStepCw();
            $productionStepCw->barcode_cw_uuid = $snListCW[$i]['barcode_cw_uuid'];
            $productionStepCw->fMONo = $fMONo;
            $productionStepCw->fGoodsID = $fGoodsID;
            $productionStepCw->save();
        }
        
        //return Db::table('v_mo_mst_cd_list')->where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
        return array(true);
    }
    
    public function toUnWriteOff($fMONo, $fGoodsID){
        if (empty($fMONo)) {
            return SFTools::err("3300", array("fMONo" => $fMONo));
        }
        if (empty($fGoodsID)) {
            return SFTools::err("3300", array("fGoodsID" => $fGoodsID));
        }
        $productionStepCw = new \backend\model\ProductionStepCw();
        /*$productionStepCwList = $productionStepCw::where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->find();
        if (empty($productionStepCwList)) {
            return SFTools::err("3307", array("productionStepCwList" => $productionStepCwList));
        }*/
        $productionStepCw::where('fMONo', $fMONo)->where('fGoodsID', $fGoodsID)->delete();
        
        return array(true);
    }
    
    /**
     * 获取
     * @param   无
     */
    public function getNotUseCW(){
        $where = new Where();
        $where['fMONo'] = ['null'];
        $groupList = Db::table('v_sn_list_cw')->field('fModelCodeCW,COUNT(*) fCount')->where($where)->group('fModelCodeCW')->select();
        $returnArr = array();
        foreach ($groupList as $key => $val) {
            $returnArr[$val['fModelCodeCW']] = intval($val['fCount']);
        }
        
        return $returnArr;
    }
    
    /**
     * 导出Excel
     * @param
     * @param
     * @param
     * */
    public function exportExcel($keyword, $fPlanDate, $fStartDate, $fEndDate, $cw, $ct, $wg){
        
        $moList = $this->getMoList($keyword, $fPlanDate, $fStartDate, $fEndDate, $cw, $ct, $wg, 1, 30000);
        if (empty($moList)) {
            return false;
        }
        $columns = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'L'); //容器
        $title = array(array('fPlanEndDate', '计划生产交期'), array('fOpenDate', '开令时间'), array('fMONo', '制令编号'), array('fGoodsID', '商品ID'), array('fGoodsCode', '商品品号'), array('fModelNameCT', '床套名称'), array('fModelNameCW', '床网名称'), array('fProcessCW', '打底工艺'), array('sort', '排序权重（越大越前）'), array('fProStkInQty', '完工入库'), array('fMoQty', '总量'), array('fStep01', '车缝完工'), array('fStep02', '实际使用床网')); //标题
        $excel = new \external\Excel();
        $excel->exportExcel($columns, $title, $moList);
    }
    
    /**
     * 导入Excel
     * @param
     * @param
     * @param
     * */
    public function importExcel($fFileFind){
        
        $file = $fFileFind['tmp_name'];
        $fFileName = $fFileFind['name'];
        $fFileTypes = explode(".", $fFileName);
        $fFileType = strtolower($fFileTypes[count($fFileTypes) - 1]);
        if (!($fFileType == "xls" || $fFileType == "xlsx")) {
            return SFTools::err("3300");
        }
        $fSavePath = './upload/excel/';
        if (!is_dir($fSavePath)) {
            if (!mkdir($fSavePath, 0755, true)) {
                return SFTools::err("3300");
            }
        }
        $FileNameStr = SFTools::getTimestamp();
        $fSaveFilePath = $fSavePath . $FileNameStr . '.' . $fFileType;
        if (!copy($file, $fSaveFilePath)) {
            return SFTools::err("3300");
        }
        $excel = new \external\Excel();
        $data = $excel->importExcel($fSaveFilePath);
        unlink($fSaveFilePath);
        if ($data === false) {
            return SFTools::err("3300");
        }
        $SUCC = 0;
        $FAIL = 0;
        foreach ($data as $key => $val) {
            if(empty($val[2]) || empty($val[3])) {
                $FAIL++;
            }else{
                $fMONo = trim($val[2]);
                $fGoodsID = trim($val[3]);
                $fProcessCW = trim($val[7]);
                $sort = intval(trim($val[8]));
                $result = $this->editProductionStepBuyfMONoANDfGoodsID($fMONo, $fGoodsID, $fProcessCW, $sort);
                if (empty($result['error_code'])) {
                    $SUCC++;
                } else {
                    $FAIL++;
                }
            }
        }
        
        return array('succ' => $SUCC, 'fail' => $FAIL);
        /*$columns = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'); //容器
        $title = array(array('fPlanEndDate', '计划生产交期'), array('fOpenDate', '开令时间'), array('fMONo', '制令编号'), array('fGoodsID', '商品ID'), array('fGoodsCode', '商品品号'), array('fModelNameCT', '床套名称'), array('fModelNameCW', '床网名称'), array('sort', '排序权重（越大越前）'), array('fProStkInQty', '完工入库'), array('fMoQty', '总量'), array('fStep01', '车缝完工'), array('fStep02', '实际使用床网')); //标题
        $excel = new \external\Excel();
        $excel->exportExcel($columns, $title, $moList);*/
    }
    
    /**
     * 导出PDF
     * @param
     * @param
     * @param
     * */
    public function exportPDF($fGoodsID, $fProcessCW, $fQtyCW){
        $productionBom = new \backend\model\ProductionBom;
        $productionBomFind = $productionBom::where('fGoodsID', $fGoodsID)->find();
        if (empty($productionBomFind)) {
            return false;
        }
        $fModelNameCT = $productionBomFind['fModelNameCT'];
        $fModelNameCW = $productionBomFind['fModelNameCW'];
        $fModelCodeCT = $productionBomFind['fModelCodeCT'];
        if($productionBomFind['fProcessCW'] != $fProcessCW){
            $productionBomFind->fProcessCW = $fProcessCW;
            $productionBomFind->save();
        }
        if(empty($fModelNameCW)){
            $fModelNameCW = '无';
            if(empty($fProcessCW)){
                $fProcessCW = '无';
            }
        }else{
            if(empty($fProcessCW)){
                $fProcessCW = '未知';
            }
        }
        $data = array();
        //$html = '<div>';
        //$html = '<hr /><span>床套名称：' . $fModelNameCT . '</span>';
        $html = '<hr />';
        $html .= '<span>床网名称：' . $fModelNameCW . '</span>';
        $html .= '<hr />';
        $html .= '<span>打底工艺：' . $fProcessCW . '</span>';
        $html .= '<hr />';
        //$html .= '</div>';
        $date = date('md', time());
    
        for ($i = 1; $i <= $fQtyCW; $i++) {
            $info = array();
            $barcode = array();
            $no = str_pad($i,3,"0",STR_PAD_LEFT);
    
            $code = $fModelCodeCT . $no . $date;
            $barcode['code'] = $code;
            $barcode['x'] = 5;
            $barcode['y'] = 3;
            $barcode['w'] = 60;
            $barcode['h'] = 10;
            $html_str = '<span>&nbsp;</span><br /><span>' . $code . '</span><br /><br />' . $html;
            $info['html'] = $html_str;
            $info['barcode'] = $barcode;
            $data[] = $info;
        }
        
        $pdf = new \external\TcPDF();
        $pdf->exportPDF_pages($data, array(70, 90), $fQtyCW);
    }
}